package guoan.utils;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * 修改备注：
 * 
 * @version 1.0
 * 
 */
public class CommonUtils {

	/**
	 * 将字符串用MD5加密
	 * 
	 * @param str
	 * @return String
	 */
	public static String md5(String source) {
		Log logger = LogFactory.getLog(CommonUtils.class);
		StringBuffer sb = new StringBuffer(32);

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(source.getBytes("utf-8"));

			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
			}
		} catch (Exception e) {
			logger.error("Can not encode the string '" + source + "' to MD5!", e);
			return null;
		}
		return sb.toString();
	}

	/**
	 * 将用户名和密码用MD5加密
	 * 
	 * @param str
	 * @return String
	 */
	public static String md5(String username, String password) {
		// 加密后欲存入数据库的密码
		return CommonUtils.md5(CommonUtils.md5(username) + CommonUtils.md5(password));
	}

	/**
	 * 产生12位用户的初始密码
	 * 
	 * @return
	 */
	public static String randomPassword() {
		String uuidStr = UUID.randomUUID().toString();
		return uuidStr.substring(uuidStr.lastIndexOf("-") + 1);
	}

	/**
	 * 字符串是否为空
	 * 
	 * @param val
	 * @return boolean true:为空,false:不为空
	 */
	public static boolean isEmpty(String val) {
		return null == val || "".equals(val.trim());
	}

	/**
	 * 取得上传文件的扩展名
	 * 
	 * @return String fileName上传文件的名字
	 */
	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	/**
	 * 获得给定数字的符号(正数返回1.0, 负数返回-1.0, 0返回0.0)
	 * 
	 * @param value
	 *            数值
	 * @return
	 */
	public static double signum(double value) {
		if (value > 0) {
			return 1.0;
		} else if (value < 0) {
			return -1.0;
		} else {
			return 0;
		}
	}

	/**
	 * 对给定的数字进行四舍五入
	 * 
	 * @param value
	 *            数值
	 * @param scale
	 *            小数点后位数
	 * @return
	 */
	public static double roundHE(double value, int scale) {
		double s = signum(value);
		double c = Math.pow(10, scale);
		value = Math.abs(value) * c;
		if (value % 2 < 1) {
			return s * (Math.ceil(Math.max(value - 0.5d, 0)) / c);
		} else {
			return s * (Math.floor(value + 0.5) / c);
		}
	}

	public static String[] findNotEq(String[] InitProducts, String[] deleteProducts) {

		Object object = new Object();
		Map<String, Object> map = new HashMap<String, Object>();

		for (String init : InitProducts) {
			map.put(init, object);
		}

		for (String delete : deleteProducts) {
			if (map.get(delete) != null)
				map.remove(delete);
		}

		String[] newProducts = new String[map.size()];
		map.keySet().toArray(newProducts);

		return newProducts;
	}
}
